import cv2
import numpy as np
import matplotlib.pyplot as plt
import colour
import IQA
from uitls import neg2post

def _getAB(x0,x1,y0,y1):
    A = (y1-y0)/(x1-x0)
    b = y0-A*x0
    return A,b

def _getxy(A0,A1,b0,b1):
    x = (b0-b1)/(A1-A0)
    y = A0*x+b0
    return x,y

def show_color_img(img):
    # img = cv2.imread(r'C:\Users\chang_ding\Desktop\2.jpg')
    img_bin = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
    img_bin[img_bin<50] = 0

    kernel = np.ones((3,3),np.uint8)
    img_erode = cv2.erode(img_bin,kernel)

    # max tidu
    img_candy = cv2.Canny(img_erode,30,150)

    r, c = img_candy.shape
    # resize
    # img_candy_resized = cv2.resize(img_candy, [int(c/2), int(r/2)])


    # 预设四条直线逼近
    mask = np.where(img_candy!=0)

    # 上
    # 寻找最大点
    miny = min(mask[0])
    cord = np.where(mask[0] == miny)
    x0 = mask[0][cord[0][0]]
    y0 = mask[1][cord[0][0]]
    num = []
    maxN = 0
    record = 0
    for idx in range(20):
        x_iter = x0 + idx
        points = np.where(img_candy[x_iter, ...]!=0)
        num.append(len(points[0]))
        if maxN < len(points[0]):
            maxN = len(points[0])
        if maxN*0.3 > len(points[0]):
            record = idx
            break
    line = img_candy[x0 + record, ...]
    if y0 > c/2: # 右侧
        x1 = x0 + record
        maskline = np.where(line!=0)
        y1 = maskline[0][0]
    elif y0<=c/2:
        x1 = x0 + record
        maskline = np.where(line!=0)
        y1 = maskline[0][-1]


    # 下
    # 寻找最大点
    maxy = max(mask[0])
    cord = np.where(mask[0] == maxy)
    x2 = mask[0][cord[0][0]]
    y2 = mask[1][cord[0][0]]
    num = []
    maxN = 0
    record = 0
    for idx in range(20):
        x_iter = x2 - idx
        points = np.where(img_candy[x_iter, ...]!=0)
        num.append(len(points[0]))
        if maxN < len(points[0]):
            maxN = len(points[0])
        if maxN*0.3 > len(points[0]):
            record = idx
            break
    line = img_candy[x2 - record, ...]
    if y2 > c/2: # 右侧
        x3 = x2 - record
        maskline = np.where(line != 0)
        y3 = maskline[0][0]
    elif y2 <= c/2:
        x3 = x2 - record
        maskline = np.where(line != 0)
        y3 = maskline[0][-1]


    # 左
    # 寻找最小点
    minx = min(mask[1])
    cord = np.where(mask[1] == minx)
    x4 = mask[0][cord[0][0]]
    y4 = mask[1][cord[0][0]]
    num = []
    maxN = 0
    record = 0
    for idx in range(40):
        y_iter = y4 + idx
        points = np.where(img_candy[..., y_iter]!=0)
        num.append(len(points[0]))
        if maxN < len(points[0]):
            maxN = len(points[0])
        if maxN*0.3 > len(points[0]):
            record = idx
            break
    line = img_candy[..., y4 + record]
    if x4 > r/2: # 下侧
        y5 = y4 + record
        maskline = np.where(line!=0)
        x5 = maskline[0][0]
    elif x4<=r/2:
        y5 = y4 + record
        maskline = np.where(line!=0)
        x5 = maskline[0][-1]


    # 右
    # 寻找最大点
    maxx = max(mask[1])
    cord = np.where(mask[1] == maxx)
    x6 = mask[0][cord[0][0]]
    y6 = mask[1][cord[0][0]]
    num = []
    maxN = 0
    record = 0
    for idx in range(40):
        y_iter = y6 - idx
        points = np.where(img_candy[..., y_iter]!=0)
        num.append(len(points[0]))
        if maxN < len(points[0]):
            maxN = len(points[0])
        if maxN*0.1 > len(points[0]): # 直线选取阈值
            record = idx
            break
    line = img_candy[..., y6 - record]
    if x6 > r/2: # 下侧
        y7 = y6 - record
        maskline = np.where(line!=0)
        x7 = maskline[0][0]
    elif x4<=r/2:
        y7 = y6 - record
        maskline = np.where(line!=0)
        x7 = maskline[0][-1]

    A0,b0 = _getAB(y0,y1,x0,x1) # 上
    A1,b1 = _getAB(y2,y3,x2,x3) # 下
    A2,b2 = _getAB(y4,y5,x4,x5) # 左
    A3,b3 = _getAB(y6,y7,x6,x7) # 右

    xx0,yy0 = _getxy(A0,A2,b0,b2) # 上左
    xx1,yy1 = _getxy(A0,A3,b0,b3) # 上右
    xx2,yy2 = _getxy(A2,A1,b2,b1) # 下左
    xx3,yy3 = _getxy(A3,A1,b3,b1) # 下右

    # pts_src = np.float32([[yy0, xx0], [yy1, xx1], [yy2, xx2], [yy3, xx3]])
    pts_src = np.float32([[xx0,yy0],[ xx1,yy1],[ xx2,yy2], [xx3,yy3]])
    pts_dst = np.float32([[0, 0], [500, 0],[0, 1000], [500, 100]])
    # 计算仿射变换矩阵
    M = cv2.getAffineTransform(pts_src[:3], pts_dst[:3])
    # 获取原始图像的尺寸（行数和列数）
    rows, cols = img_bin.shape[:2]
    # 进行仿射变换
    image_affine = cv2.warpAffine(img, M, (500, 1000))

    # 评估
    # 亮度评估
    image_brt = cv2.cvtColor(image_affine,cv2.COLOR_RGB2GRAY)
    record = IQA.low_frq_uniformity_assessment(image_brt)
    print('亮度均一性:' + str(record))

    # 色度评估
    # img_assess = np.float32(image_affine)/255
    img_assess = image_affine
    img_CIEx = np.zeros([1000,500])
    img_CIEy = np.zeros([1000,500])

    # 将RGB数据转换为CIE xy坐标
    for i in range(1000):
        for j in range(500):
            r = img_assess[i, j, 2]
            g = img_assess[i, j, 1]
            b = img_assess[i, j, 0]

            X = 0.4124564 * r + 0.3575761 * g + 0.180437 * b
            Y = 0.2126729 * r + 0.7151522 * g + 0.072175 * b
            Z = 0.0193339 * r + 0.1191920 * g + 0.950304 * b

            x = X / (X + Y + Z)
            y = Y / (X + Y + Z)
            img_CIEx[i, j] = x
            img_CIEy[i, j] = y
    img_CIEx = np.reshape(img_CIEx,(1,500*1000))
    img_CIEy = np.reshape(img_CIEy,(1,500*1000))

    # 计算色度偏差程度
    img_CIEx = neg2post.neg2post(img_CIEx)
    img_CIEy = neg2post.neg2post(img_CIEy)
    diffx = np.mean(np.abs(img_CIEx-0.33))
    diffy = np.mean(np.abs(img_CIEy-0.33))

    plt.figure()
    plt.imshow(image_affine)
    plt.figure()
    plt.imshow(img_bin)


    colour.plotting.plot_chromaticity_diagram_CIE1931(standalone=False)
    plt.plot(img_CIEx[0,...],img_CIEy[0,...],'ko',markersize=1,alpha=0.5)
    # plt.axis([-0.1,1,-0.1,1])
    plt.show()

    # plt.figure(),plt.imshow(img_candy)
    # plt.plot([y0,y1],[x0,x1],'r*-')
    # plt.plot([y2,y3],[x2,x3],'g*-')
    # plt.plot([y4,y5],[x4,x5],'b*-')
    # plt.plot([y6,y7],[x6,x7],'y*-')

    return record, diffx, diffy

